var supplierObj = [];
var limit = 15;
var tid, itemIndex = 9;
var bizType = 'lab_level_optimize';
var addFiles = new Object();
var seasonTypeObj = convertEnumToObj(seasonTypeList);
var strengthObj = new Object(),snMaterialObj = new Object(),cjMaterialObj = new Object(),pzMaterialObj = new Object(),
    xjMaterialObj = new Object(),chMaterialObj = new Object(),sMaterialObj = new Object(),wjMaterialObj = new Object(),
    materialObj = new Object(),strengthObj = new Array(),dosageObj = new Object();
var materialTypeObj = convertEnumToObj(materialTypeList);
var materialArray = new Array();//材料添加列表
var snHtml='<option value="">请选择水泥材料</option>',xjHtml='<option value="">请选择细集料</option>',
    cjHtml='<option value="">请选择粗集料</option>',sHtml='<option value="">请选择水</option>',
    chHtml='<option value="">请选择掺和料</option>',wjHtml='<option value="">请选择外加剂</option>',
    pzHtml='<option value="">请选择配重材料</option>',mtHtml = '<option value="">请选择材料类型</option>',
    allHtml = '<option value="">请选择材料</option>';
layui.use(['laypage', 'table', 'upload', 'form', 'laydate'], function(){
    var table = layui.table,upload = layui.upload,laydate = layui.laydate;
    var form = layui.form;
    if (dosageList != null) {
        $.each(dosageList, function (index, val) {
            dosageObj[val.strengthId] = val;
        });
    }
    $.each(materialTypeList, function (index, val) {
        mtHtml += '<option value="' + val.id + '">' + val.name + '</option>';
    });
    $.each(strengthList, function (index, val) {
        strengthObj[val.id] = val;
    });
    $.each(materialList, function (index, val) {
        materialObj[val.id] = val;
        var norms = val.fullName;
        if (!isNull(val.brand)) {
            norms += '(' + val.brand + ')';
        }
        if (val.type == 2){//水泥
            snMaterialObj[val.id] = val;
            snHtml +='<option value="' + val.id + '">' + norms + '</option>';
        }else if (val.type == 3){//细集料
            xjMaterialObj[val.id] = val;
            xjHtml +='<option value="' + val.id + '">' + norms + '</option>';
        }else if (val.type == 4){//粗集料
            cjMaterialObj[val.id] = val;
            cjHtml +='<option value="' + val.id + '">' + norms + '</option>';
        }else if (val.type == 5){//掺和料
            chMaterialObj[val.id] = val;
            chHtml +='<option value="' + val.id + '">' + norms + '</option>';
        }else if (val.type == 6){//外加剂
            wjMaterialObj[val.id] = val;
            wjHtml +='<option value="' + val.id + '">' + norms + '</option>';
        }else if (val.type == 7){//水
            sMaterialObj[val.id] = val;
            sHtml +='<option value="' + val.id + '">' + norms + '</option>';
        }else if (val.type == 9) {//配重材料
            pzMaterialObj[val.id] = val;
            pzHtml +='<option value="' + val.id + '">' + norms + '</option>';
        }
        allHtml +='<option value="' + val.id + '">' + norms + '</option>';
    });
    setTimeout(function () {
        init();
    }, 300);
    
    laydate.render({
        elem: '#add-inspectionDate',
        type: 'datetime',
        done: function(value, date, endDate){
            // console.log(value); // 日期字符，如： 2017-08-18
            // console.log(date); // 包含年月日时分秒各项值的对象
            // console.log(endDate); // 结束日期时间对象，当设置 range 时才会返回。对象成员同上。
        }
    });
    laydate.render({
        elem: '#add-takeEffectDate',
        type: 'datetime',
        done: function(value, date, endDate){
        }
    });

    let todoCols = [
        [
            {field: 'id', title: '标识', width:80, align: 'center', hide: true}
            ,{field: 'code', title: '配合比代号', width:140, align: 'center'}
            ,{field: 'labCode', title: '试验室代号', width:140, align: 'center'}
            ,{field: 'strengthId', title: '强度等级', width: 120, align: 'center', templet:function (val) {
                var strengthLevel = strengthObj[val.strengthId];
                if (strengthLevel != null) {
                    return strengthLevel.strength;
                }
                return '';
            }}
            ,{field: 'strengthId', title: '基础强度', width:120, align: 'center', templet:function (val) {
                var obj = strengthObj[val.strengthId];
                console.log(obj)
                if (obj != null && obj.levelId > 0 && strengthObj[obj.levelId] != null) {
                    return strengthObj[obj.levelId].strength;
                }
                return '';
            }}
            ,{field: 'designSlump', title: '坍落度', width:120, align: 'center'}
            ,{field: 'ratio1', title: '水灰比', width:120, align: 'center'}
            ,{field: 'ratio2', title: '水胶比', width:120, align: 'center'}
            ,{field: 'volumeWeight', title: '容重(kg)', width:140, align: 'center'}
            ,{field: 'status', title: '状态', width:80, align: 'center', templet:function (val) {
                if (val.status == 0)
                    return '启用';
                else
                    return '禁用';
            }}
            ,{field: 'createTime', title: '创建时间', width:140, align: 'center'}
            ,{field: 'remark', title: '备注', width: 240, align: 'center'}
            ,{fixed: 'right', title:'操作', width: 150, align:'center', templet:function (val) {
                var str = '';
                if (val.enable == 0)
                    str = '<a lay-event="delete" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-danger">禁用</a>';
                else
                    str = '<a lay-event="delete" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-normal">启用</a>';
                str += '<a lay-event="edit" href="javascript:void(0)" class="layui-btn layui-btn-xs">编辑</a>';
                return str;
            }}
        ]
    ];

    table.render({
        elem: '#body-list'
        ,url: '/lab/level-optimize/page'
        ,method: 'post'
        ,page: true
        ,cols: todoCols
        ,limit: limit
        ,limits: [15,30,50,100]
        ,request: {
            pageName: 'curr' //页码的参数名称，默认：page
            ,limitName: 'limit' //每页数据量的参数名，默认：limit
        }
        ,where: {
            offset: 0,
            limit: limit
        }
        ,parseData: function(res){ //res 即为原始返回的数据
            console.log(res)
            if (res.code == 0 && res.data != null) {
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            } else {
                return {
                    "code": res.code, //解析接口状态
                    "msg": '没有任何数据', //解析提示文本
                    "count": 0, //解析数据长度
                    "data": '' //解析数据列表
                };
            }
        }
    });

    //监听行工具事件
    table.on('tool(body-list)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var data = obj.data //获得当前行数据
            ,layEvent = obj.event; //获得 lay-event 对应的值
        if(layEvent === 'delete'){
            var id = data.id;
            var status = data.enable;
            var tip = '是否要启用？';
            if (status == 0)
                tip = '是否要停用？';
            layer.confirm(tip, {
                btn: ['确定', '取消']
            }, function(index, layero){
                var updateStatus = 0;
                if (status == 0)
                    updateStatus = 1;
                var option = {
                    id: id,
                    status: updateStatus
                };
                console.log(option)
                save(option, "/lab/level-optimize/update-status/" + id, 0,'application/x-www-form-urlencoded');
                layer.close(index);
            });
        } else if(layEvent === 'edit'){
            tid = data.id;
            updateWindow(data);
            form.render(data);
        }
    });
    table.on('rowDouble(body-list)', function(obj){
        var data = obj.data;
        tid = data.id;
        updateWindow(data);
    });
    form.on('select(add-materialType)', function(data) {//操作下拉选择框信息
        var elem = data.elem;
        var index = $(elem).attr('data-value');
        if (data.value != null) {
            var html = convertMaterial(data.value);
            $('.material-body-list').find('.add-material' + index).html(html);
            form.render();
        }
    });
    form.on('select(search-enable)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(search-strength)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(search-material)', function(data) {
        $(".btn-query").trigger("click");
    });
    form.on('select(add-strength)', function(data) {
        var levelId = $('.addModal .add-strength').find("option:selected").attr('data-levelId');
        if (levelId != null) {
            if (dosageObj != null) {
                var dosageData = dosageObj[levelId];
                if (dosageData != null) {
                    $('.addModal .add-minDosage').val(dosageData.minDosage);
                    $('.addModal .add-maxDosage').val(dosageData.maxDosage);
                }
            }
        }
    });
    $('.btn-query').on('click', function () {//搜索按钮
        var searchVal = $('.search-text').val();
        var orgId = $('.search-origin').val();
        var strengthId = $('.search-strength').val();
        var status = $('.search-enable').val();
        var option = {page:1,limit:limit};
        if (!isNull(searchVal))
            option['searchVal'] = searchVal;
        if (!isNull(status))
            option['status'] = status;
        if (!isNull(orgId))
            option['orgId'] = orgId;
        if (strengthId != null)
            option['strengthId'] = strengthId;
        console.log(option)
        table.reload('body-list', {
            where: option,page:{curr:1}
        });
    });

    $('.btn-add').on('click', function () {
        $('.addModal').show();
        init();
    });
    $(".addModal .close").on("click", function() {
        $(".addModal").hide();
        $(".addModal input").val("");
        $(".addModal select").val("");
        $(".addModal textarea").val("");
        tid = -1;
        form.render();
    });
    $('.material-body-list').on('click', '.btn-remove', function () {
        var index_ = $(this).attr('data-value');
        // console.log(index_);
        if (index_ != null) {
            layer.confirm('是否需要移除子项~?', {
                btn: ['确定', '取消']
            }, function(index, layero){
                var removeName = 'material-item' + index_;
                var itemId = $('.material-body-list').find('.add-used' + index_).attr('data-id');
                if (itemId > 0) {
                    var flag = 0;
                    var isSj = $('.add-sj').val();
                    $.each(materialArray, function (index, val) {//组装明细
                        console.log(val);
                        var materialType = $('.material-body-list').find('.add-materialType' + index).val();
                        var materialId = $('.material-body-list').find('.add-material' + index).val();
                        var used = $('.material-body-list').find('.add-used' + index).val();
                        if (used == null)
                            used = 0;
                        if (materialType != null && materialId != null && used != null) {
                            if (materialType == 2 && index != index_) {
                                materialArray.splice(index, 1);
                                flag = 1;;
                            }
                        }
                    });
                    if (isSj == 0) {
                        if (flag == 0) {
                            layer.msg('非润管砂浆必须填入水泥用量~！');
                            return;
                        }
                    }
                    var option = {id:itemId,status:1,removeName:removeName,index:index_};
                    save(option, '/lab/level-optimize/update-material-status', 1, 'application/x-www-form-urlencoded');
                } else {
                    $('.material-body-list').find('.' + removeName).remove();
                    form.render();
                    layer.close(index);
                    $.each(materialArray, function (i, val) {
                        if (val != null) {
                            if (val == index_) {
                                materialArray.splice(i, 1);
                            }
                        }
                    });
                }
            });
        }
    });
    $('.btn-material-add').on('click', function () {//添加材料子项
        var html = buildHtml(itemIndex, 0, 0, -1);
        $('.material-body-list').append(html);
        $('.material-body-list').find('.add-materialType' + itemIndex).val(0);
        form.render();
        materialArray.push(itemIndex);
        itemIndex++;
    });
    $('.addModal').on('keyup','.add-used-key', function () {
        validateMealStandard(this);
        var addUsed = $('.addModal .add-used-key');
        var sumDosage = 0;
        $.each(addUsed, function (index, val) {
            var used = $(val).val();
            if (used != null)
                sumDosage = parseFloat(sumDosage) + parseFloat(used);
        });
        $('.add-volumeWeight').val(parseFloat(sumDosage).toFixed(1));
    });
    //点击添加提交
    form.on('submit(addBtns)', function() {
        var orgId = $('.search-origin').val();
        var strengthId = $.trim($(".addModal .add-strength").val());//公司
        var mixTime = $.trim($(".addModal .add-mixTime").val());//搅拌时间
        var remark = $.trim($(".addModal .remark").val());//备注
        var code = $.trim($(".addModal .add-code").val());//
        var labCode = $.trim($(".addModal .add-labCode").val());//
        var designSlump = $.trim($(".addModal .add-designSlump").val());//设计坍落度
        var theorySlump = $.trim($(".addModal .add-theorySlump").val());//实际坍落度
        var season = $.trim($(".addModal .add-season").val());//使用季节
        var volumeWeight = $.trim($(".addModal .add-volumeWeight").val());//容重
        var ratio1 = $.trim($(".addModal .add-ratio1").val());//水灰比
        var ratio2 = $.trim($(".addModal .add-ratio2").val());//水胶比
        var sandRate = $.trim($(".addModal .add-sandRate").val());//砂率
        var mixRatio = $.trim($(".addModal .add-mixRatio").val());//配合比
        var density = $.trim($(".addModal .add-density").val());//密度
        var minDosage = $.trim($(".addModal .add-minDosage").val());//最小容重
        var maxDosage = $.trim($(".addModal .add-maxDosage").val());//最大容重
        var takeEffectDate = $.trim($(".addModal .add-takeEffectDate").val());//生效日期
        var inspectionDate = $.trim($(".addModal .add-inspectionDate").val());//生效日期
        var initialSettingTime = $.trim($(".addModal .add-initialSettingTime").val());//初凝时间
        var finalSettingTime = $.trim($(".addModal .add-finalSettingTime").val());//终凝时间
        var enable = $.trim($(".addModal .add-enable").val());//是否启用
        var isSj = 0;
        var sn= 0,xj= 0,cj=0,s=0,ch=0,wj=0;
        if (minDosage == null || minDosage < 500)
            minDosage = 2300;
        if (maxDosage == null || maxDosage < 500)
            maxDosage = 2400;
        var normsList = new Array();
        if (tid != null && tid > 0)
            volumeWeight = 0;
        if (isNull(volumeWeight) || parseInt(volumeWeight) == NaN)
            volumeWeight = 0;
        $.each(materialArray, function (index, val) {//组装明细
            var materialType = $('.material-body-list').find('.add-materialType' + index).val();
            var materialTypeText = $('.material-body-list').find('.add-materialType' + index).find("option:selected").text();
            var materialId = $('.material-body-list').find('.add-material' + index).val();
            var materialNorms = $('.material-body-list').find('.add-material' + index).find("option:selected").text();
            var used = $('.material-body-list').find('.add-used' + index).val();
            var did = $('.material-body-list').find('.add-used' + index).attr('data-id');
            if (used == null || isNull(used) || parseInt(used) == NaN)
                used = 0;
            if (materialType != null && materialId != null && used != null) {
                var obj = {orgId:orgId,materialType:materialType,materialTypeTxt:materialTypeText,materialId:materialId,
                    materialName:materialNorms,used:parseInt(used),status:0};
                if (did != null && did > 0)
                    obj['id'] = did;
                normsList.push(obj);
                if (materialType == 2) {
                    sn += parseInt(used);
                } else if (materialType == 3) {
                    xj += parseInt(used);
                } else if (materialType == 4 || materialType == 9) {
                    cj += parseInt(used);
                } else if (materialType == 5) {
                    ch += parseInt(used);
                } else if (materialType == 6) {
                    wj += parseInt(used);
                } else if (materialType == 7) {
                    s += parseInt(used);
                }
                if (used != null) {
                    volumeWeight = parseInt(used) + parseInt(volumeWeight);
                }
            }
        });
        volumeWeight = parseFloat(volumeWeight).toFixed(1);
        if (isSj == 0) {
            if (sn <= 0) {
                layer.msg('非润管砂浆必须填入水泥用量~！');
                return;
            }
        }
        if (s > 0 && sn > 0){// 水灰比计算公式：水 / 水泥 = 水灰比
            ratio1 = parseFloat(s / sn).toFixed(2);
        } else {
            ratio1 = 0;
        }
        if (s > 0 && (sn > 0 || ch > 0)) {// 水胶比计算公式： 水 / (水泥 + 参合料 + 煤灰) = 水胶比
            ratio2 = parseFloat(s / (sn + ch)).toFixed(2);
        } else {
            ratio2 = 0;
        }
        if (xj > 0 && (xj > 0 || cj > 0)) {// 砂率计算公式：砂 / (砂 + 石子) = 砂率
            sandRate = parseFloat(xj / (xj + cj)).toFixed(2);
        } else {
            sandRate = 0;
        }
        //混凝土配合比：mc0 水泥: ms0 细集料: mg0 粗集料: mf0 参合料: mFDN0 外加剂: mW0 水
        mixRatio = '1';
        if (sn > 0) {
            if (xj > 0) {
                var v = parseFloat(xj / sn).toFixed(2);
                mixRatio += ':' + v;
            } else {
                mixRatio += ':' + 0;
            }
            if (cj > 0) {
                var v = parseFloat(cj / sn).toFixed(2);
                mixRatio += ':' + v;
            } else {
                mixRatio += ':' + 0;
            }
            if (ch > 0) {
                var v = parseFloat(ch / sn).toFixed(2);
                mixRatio += ':' + v;
            } else {
                mixRatio += ':' + 0;
            }
            if (wj > 0) {
                var v = parseFloat(wj / sn).toFixed(2);
                mixRatio += ':' + v;
            } else {
                mixRatio += ':' + 0;
            }
            if (s > 0) {
                var v = parseFloat(s / sn).toFixed(2);
                mixRatio += ':' + v;
            } else {
                mixRatio += ':' + 0;
            }
        } else {//软管砂浆
            mixRatio = '';
        }
        if (normsList == null || normsList.length == 0) {
            layer.msg('请设置配比材料子项~!');
            return;
        }

        $(".addModal .add-mixRatio").val(mixRatio);//配合比
        $(".addModal .add-ratio1").val(ratio1);//水灰比
        $(".addModal .add-ratio2").val(ratio2);//水胶比
        $(".addModal .add-sandRate").val(sandRate);//砂率
        $(".addModal .add-volumeWeight").val(volumeWeight);//容重

        var options = {strengthId:strengthId, code:code,designSlump:designSlump,theorySlump:theorySlump,
        remark:remark,mixTime:mixTime,volumeWeight:volumeWeight,season:season,minDosage:minDosage,maxDosage:maxDosage,
        ratio1:ratio1,sandRate:sandRate,mixRatio:mixRatio,density:density,ratio2:ratio2,labCode:labCode,
        takeEffectDate:takeEffectDate,inspectionDate:inspectionDate,initialSettingTime:initialSettingTime,
        finalSettingTime:finalSettingTime,enable:enable,status:0,orgId:orgId,list:normsList};
        console.log(options)
        if (isNull(code)) {
            layer.msg("请输入配合比代号！");
            return ;
        }
        if (strengthId == null) {
            layer.msg("请选择强度等级！");
            return ;
        }
        if (volumeWeight == null) {
            layer.msg("请设置配合比子项！");
            return ;
        }
        if (mixTime == null || mixTime < 10) {
            layer.msg("请设置搅拌时间且搅拌时间不能小于10秒！");
            return ;
        }
        if (tid != null && tid > 0) {
            options['id'] = tid;
            save(JSON.stringify(options), '/lab/level-optimize/update', 0,'application/json');
        } else {
            save(JSON.stringify(options), '/lab/level-optimize/save', 0,'application/json');
        }
    });

    function save(option, url, type, contentType) {//新增或修改
        var loading = layer.load(1);
        $.ajax({
            url: url,
            type: 'put',
            dataType: 'json',
            data:option,
            contentType: contentType,
            timeout: 30000,
            success: function(res) {
                layer.close(loading);
                if(res.code == 0) {
                    if (type == 0) {
                        layer.msg("更新成功!");
                        table.reload('body-list', { where: {offset: 0,page:1,
                                limit: limit,
                                searchVal:$('.search-text').val(),
                                strengthId:$('.search-strength').val(),status:$('.search-enable').val()},page:{curr:1} });
                        setTimeout(function () {
                            $(".addModal").hide();
                            $(".addModal input").val("");
                            $(".addModal select").val("");
                            $(".addModal textarea").val("");
                            form.render();
                        }, 3000);
                    } else if (type == 1) {
                        layer.msg("更新成功!");
                        $('.material-body-list').find('.' + option.removeName).remove();
                        form.render();
                        $.each(materialArray, function (i, val) {
                            if (val != null) {
                                if (val == option.index) {
                                    materialArray.splice(option.index, 1);
                                }
                            }
                        });
                        restLevel();
                    }
                } else {
                    layer.msg(res.msg);
                    return;
                }
            },
            error: function(res) {
                layer.msg("请求失败，请稍后再试！");
                layer.close(loading);
                return;
            },
            complete: function(XMLHttpRequest, status) {
                if(status == 'timeout') {
                    layer.msg("请求超时，请稍后再试！");
                    layer.close(loading);
                    return;
                }
            }
        })
    }
    function loadMaterial(option, url) {
        var loading = layer.load(1);
        $.ajax({
            url: url,
            type: 'post',
            dataType: 'json',
            data:option,
            timeout: 30000,
            success: function(res) {
                layer.close(loading);
                if(res.code == 0 && res.data != null) {
                    var data = res.data;
                    materialArray = new Array();
                    var html = '';
                    $.each(data, function (index, val) {
                        if (val.materialType != null) {
                            html += buildHtml(index, val.materialType, val.used, val.id);
                        }
                        materialArray.push(index);
                    });
                    itemIndex = data.length;
                    $('.material-body-list').html(html);
                    form.render();
                    $.each(data, function (index, val) {
                        if (val.materialType != null) {
                            $('.material-body-list').find('.add-materialType' + index).val(val.materialType);
                        }
                        if (val.materialId != null) {
                            $('.material-body-list').find('.add-material' + index).val(val.materialId);
                        }
                    })
                    form.render();
                } else {
                    layer.msg(res.msg);
                    return;
                }
            },
            error: function(res) {
                layer.msg("请求失败，请稍后再试！");
                layer.close(loading);
                return;
            },
            complete: function(XMLHttpRequest, status) {
                if(status == 'timeout') {
                    layer.msg("请求超时，请稍后再试！");
                    layer.close(loading);
                    return;
                }
            }
        })
    }
    function restLevel() {
        var sn= 0,xj= 0,cj=0,s=0,ch=0,wj=0;
        var mixRatio = $(".addModal .add-mixRatio").val();//配合比
        var ratio1 = $(".addModal .add-ratio1").val();//水灰比
        var ratio2 = $(".addModal .add-ratio2").val();//水胶比
        var sandRate = $(".addModal .add-sandRate").val();//砂率
        var volumeWeight = 0;//容重
        var strengthId = $.trim($(".addModal .add-strength").val());//公司
        var mixTime = $.trim($(".addModal .add-mixTime").val());//搅拌时间
        $.each(materialArray, function (index, val) {//组装明细
            var materialType = $('.material-body-list').find('.add-materialType' + index).val();
            var materialId = $('.material-body-list').find('.add-material' + index).val();
            var used = $('.material-body-list').find('.add-used' + index).val();
            if (used == null)
                used = 0;
            if (materialType != null && materialId != null && used != null) {
                if (materialType == 2) {
                    sn += parseFloat(used);
                } else if (materialType == 3) {
                    xj += parseFloat(used);
                } else if (materialType == 4 || materialType == 9) {
                    cj += parseFloat(used);
                } else if (materialType == 5) {
                    ch += parseFloat(used);
                } else if (materialType == 6) {
                    wj += parseFloat(used);
                } else if (materialType == 7) {
                    s += parseFloat(used);
                }
                if (used != null && used > 0)
                    volumeWeight = parseFloat(used) + parseFloat(volumeWeight);
            }
        });
        volumeWeight = parseFloat(volumeWeight).toFixed(1);

        if (s > 0 && sn > 0){// 水灰比计算公式:水 / 水泥 = 水灰比
            ratio1 = parseFloat(s / sn).toFixed(2);
        } else {
            ratio1 = 0;
        }
        if (s > 0 && (sn > 0 || ch > 0)) {// 水胶比计算公式: 水 / (水泥 + 参合料 + 煤灰) = 水胶比
            ratio2 = parseFloat(s / (sn + ch)).toFixed(2);
        } else {
            ratio2 = 0;
        }
        if (xj > 0 && (xj > 0 || cj > 0)) {// 砂率计算公式:砂 / (砂 + 石子) = 砂率
            sandRate = parseFloat(xj / (xj + cj)).toFixed(2);
        } else {
            sandRate = 0;
        }
        //混凝土配合比:mc0 水泥: ms0 细集料: mg0 粗集料: mf0 参合料: mFDN0 外加剂: mW0 水
        mixRatio = '1';
        if (sn > 0) {
            if (xj > 0) {
                var v = parseFloat(xj / sn).toFixed(2);
                mixRatio += ':' + v;
            } else {
                mixRatio += ':' + 0;
            }
            if (cj > 0) {
                var v = parseFloat(cj / sn).toFixed(2);
                mixRatio += ':' + v;
            } else {
                mixRatio += ':' + 0;
            }
            if (ch > 0) {
                var v = parseFloat(ch / sn).toFixed(2);
                mixRatio += ':' + v;
            } else {
                mixRatio += ':' + 0;
            }
            if (wj > 0) {
                var v = parseFloat(wj / sn).toFixed(2);
                mixRatio += ':' + v;
            } else {
                mixRatio += ':' + 0;
            }
            if (s > 0) {
                var v = parseFloat(s / sn).toFixed(2);
                mixRatio += ':' + v;
            } else {
                mixRatio += ':' + 0;
            }
        } else {//软管砂浆
            mixRatio = '';
        }
        $(".addModal .add-mixRatio").val(mixRatio);//配合比
        $(".addModal .add-ratio1").val(ratio1);//水灰比
        $(".addModal .add-ratio2").val(ratio2);//水胶比
        $(".addModal .add-sandRate").val(sandRate);//砂率
        $(".addModal .add-volumeWeight").val(volumeWeight);//容重

        var options = {strengthId:strengthId,mixTime:mixTime,id:tid,mixRatio:mixRatio,ratio1:ratio1,
            ratio2:ratio2,sandRate:sandRate,volumeWeight:volumeWeight};

        save(JSON.stringify(options), '/lab/level-optimize/update', 0,'application/json');
    }
    updateUploadListIns = upload.render({
        elem: '.uploadEnclosure',
        accept:"file",
        url: '/file/upload?bizId=-12&bizType=' + bizType,
        /*auto: false,*/
        multiple: true,
        size:10 * 1024 * 2,
        bindAction: '#addEnclosureAction',
        choose: function(obj){
            //预读本地文件示例，不支持ie8
            obj.preview(function(index, file, result){
                let fileName = file.name;
                // 拼接内容
                let html = "<div style='display: inline-block'>"
                if(isAssetTypeAnImage(fileName)){
                    html += '<img src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img downfile" id="filed-' + index + '">'
                }else {
                    html += "<a href=\"javascript:;\" class='downfile' id='filed-" + index + "'>" + fileName + "</a>";
                }
                // 删除按钮
                html += '<button type="button" data-file="12" id="file-' + index + '" class="layui-btn layui-btn-xs layui-btn-danger add-file-delete" style="margin-top: 70px"><i class="layui-icon">&#xe640;</i></button>'
                html += "</div>";
                $('.layui-upload-list').append(html);
            });
        },
        before: function(obj){ //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
            layer.load(); //上传loading
        },
        done: function(res,index){
            //上传完毕
            layer.closeAll('loading');
            // 查找出文件
            let fileDocId = "#file-" + index;
            let filedDocId = "#filed-" + index;
            if(res.code == 0){
                $(fileDocId).data("file",res.data);
                $(filedDocId).data("file",res.data);
                // addFiles.push(res.data);
                analysis({enclosureId:res.data}, "/lab/level-optimize/analysis");
            }else {
                layer.msg("上传失败:" + res.msg)
                $(fileDocId).parent().remove();
            }
        }
    });
    function analysis(option, url) {
        var loading = layer.load(1);
        $.ajax({
            url: url,
            type: 'post',
            dataType: 'json',
            data:option,
            timeout: 30000,
            success: function(res) {
                layer.close(loading);
                layer.alert(res.msg);
            },
            error: function(res) {
                layer.msg("请求失败，请稍后再试！");
                layer.close(loading);
                return;
            },
            complete: function(XMLHttpRequest, status) {
                if(status == 'timeout') {
                    layer.msg("请求超时，请稍后再试！");
                    layer.close(loading);
                    return;
                }
            }
        })
    }
    function updateWindow(data) {
        $('.addModal').show();
        $('.addModal .add-code').val(data.code);
        $('.addModal .add-strength').val(data.strengthId);
        $('.addModal .add-labCode').val(data.labCode);
        $('.addModal .add-enable').val(data.enable);
        $('.addModal .add-mixTime').val(data.mixTime);
        $('.addModal .add-season').val(data.season);
        $('.addModal .update-material').val(data.mid);
        $('.addModal .add-volumeWeight').val(data.volumeWeight);
        $('.addModal .add-ratio1').val(data.ratio1);
        $('.addModal .add-sandRate').val(data.sandRate);
        $('.addModal .add-mixRatio').val(data.mixRatio);
        $('.addModal .add-density').val(data.density);
        $('.addModal .add-ratio2').val(data.ratio2);
        $('.addModal .add-minDosage').val(data.minDosage);
        $('.addModal .add-maxDosage').val(data.maxDosage);
        $('.addModal .add-sj').val(0);
        $('.addModal .add-designSlump').val(data.designSlump);
        $('.addModal .add-theorySlump').val(data.theorySlump);
        $('.addModal .add-takeEffectDate').val(data.takeEffectDate);
        $('.addModal .add-inspectionDate').val(data.inspectionDate);
        $('.addModal .add-initialSettingTime').val(data.initialSettingTime);
        $('.addModal .add-finalSettingTime').val(data.finalSettingTime);
        $('.addModal .remark').val(data.remark);
        loadMaterial({levelConstructId:data.id}, '/lab/level-optimize/find-material');
        form.render();
    }
    function init() {
        var html = '';
        $('.add-sj').val(0);
        $('.add-enable').val(0);
        $('.add-mixTime').val(30);
        $('.add-volumeWeight').val(0);
        $('.add-ratio1').val(0);
        $('.add-sandRate').val(0);
        $('.add-density').val(0);
        $('.add-ratio2').val(0);
        $('.add-initialSettingTime').val(0);
        $('.add-finalSettingTime').val(0);
        html += buildHtml(0, 2,0,-1);//水泥
        html += buildHtml(1, 3,0,-1);//细集料
        html += buildHtml(2, 3,0,-1);//细集料
        html += buildHtml(3, 4,0,-1);//粗集料
        html += buildHtml(4, 4,0,-1);//粗集料
        html += buildHtml(5, 5,0,-1);//掺合料
        html += buildHtml(6, 5,0,-1);//掺合料
        html += buildHtml(7, 6,0,-1);//外加剂
        html += buildHtml(8, 7,0,-1);//水
        $('.material-body-list').html(html);
        form.render();
        $('.material-body-list').find('.add-materialType0').val(2);
        $('.material-body-list').find('.add-materialType1').val(3);
        $('.material-body-list').find('.add-materialType2').val(3);
        $('.material-body-list').find('.add-materialType3').val(4);
        $('.material-body-list').find('.add-materialType4').val(4);
        $('.material-body-list').find('.add-materialType5').val(5);
        $('.material-body-list').find('.add-materialType6').val(5);
        $('.material-body-list').find('.add-materialType7').val(6);
        $('.material-body-list').find('.add-materialType8').val(7);
        form.render();
        for (var i = 0; i < 9; i++) {
            materialArray.push(i);
        }
    }
    
    function buildHtml(index, type, used, itemId) {//加载动态材料列表
        var materialHtml = convertMaterial(type);
        var html = '<div class="layui-form-item material-item' + index + '">\n' +
            '<div class="layui-input-inline" style="width: 220px;">\n' +
            '<select class="add-materialType' + index + '" data-value="' + index + '" lay-search="" lay-filter="add-materialType">' + mtHtml + '</select>\n' +
            '</div>\n' +
            '<div class="layui-input-inline" data-value="' + index + '" style="width: 300px;">\n' +
            '<select class="add-material' + index + '" lay-search="" lay-filter="add-material">' + materialHtml + '</select>\n' +
            '</div>\n' +
            '<div class="layui-input-inline" style="width: 160px;">\n' +
            '<input type="text" value="' + used + '" data-id="' + itemId + '" class="layui-input add-used-key add-used' + index + '" data-value="' + index + '" placeholder="用量">\n' +
            '</div>\n' +
            '<label class="layui-form-label" style="width: 100px;">千克</label>\n' +
            '<a href="javascript:void(0)" data-value="' + index + '" lay-verify="number" class="layui-btn layui-btn-warm btn-remove" lay-filter="btn-edit">\n' +
            '<i class="layui-icon layui-icon-edit"></i>移除</a>\n' +
            '</div>';
        return html;
    }
    function convertMaterialType(type) {
        var html = '<opiton value="">请先选择材料类型</opiton>';
        $.each(materialTypeList, function (index, val) {
            console.log(val)
            if (val.id == type){//水泥
                html += '<opiton value="' + val.id + '" selected="selected">' + val.name + '</opiton>';
            }else {
                html += '<opiton value="' + val.id + '">' + val.name + '</opiton>';
            }
        });
        return html;
    }
    function convertMaterial(type) {
        if (type == 2){//水泥
            return snHtml;
        }else if (type == 3){//细集料
            return xjHtml;
        }else if (type == 4){//粗集料
            return cjHtml;
        }else if (type == 5){//掺和料
            return chHtml;
        }else if (type == 6){//外加剂
            return wjHtml;
        }else if (type == 7){//水
            return sHtml;
        }else if (type == 9) {//配重材料
            return pzHtml;
        } else {
            return allHtml; //所有材料
        }
    }

});